package com.sky.interceptor;


import com.sky.constant.JwtClaimConstant;
import com.sky.context.BaseContext;
import com.sky.exceptionHandler.JwtException;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("判断当前拦截到的是否是controller，{}", handler instanceof HandlerMethod);

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        try{
            Claims claims = JwtUtils.parseJWT(jwtProperties.getAdminSecretKey(), token);
            String empId = claims.get(JwtClaimConstant.EMP_ID).toString();
            Long id = Long.valueOf(empId);
            BaseContext.setCurrentId(id);
        }catch (Exception ex){
            String requestURI = request.getRequestURI();
            throw new JwtException(504,String.format("没有「%s」的权限",requestURI));
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

}
